import { Commit, createStore } from 'vuex'
// import { testData, testProps, PostProps } from "@/testData";
import axios, { AxiosRequestConfig } from 'axios'
// 封装get请求 Commit就是commit的类型
const getAndCommit = async (
  url: string,
  mutationName: string,
  commit: Commit
) => {
  commit('setLoading', true) // 开始
  const { data } = await axios.get(url)
  commit(mutationName, data)
  // await new Promise((resolve) => setTimeout(resolve, 3000));
  // commit("setLoading", false); //结束
}

// 封装post请求
const postAndCommit = async (
  url: string,
  mutationName: string,
  commit: Commit,
  payload: any
) => {
  const { data } = await axios.post(url, payload) // main里面的请求
  commit(mutationName, data)
}
// 所有的
const asyncAndCommit = async (
  url: string,
  mutationName: string,
  commit: Commit,
  config: AxiosRequestConfig = { method: 'get' }
) => {
  const { data } = await axios(url, config)
  commit(mutationName, data)
  return data
}
// 图片描述
export interface ImageProps {
  _id?: string
  url?: string
  createAt?: string
}
export interface UserProps {
  // 当前是否登录
  isLogin: boolean
  nickName?: string
  _id?: string
  column?: string // 用户自己的专栏ID
  avatar?: ImageProps
  description?: string
}

export interface ColumnProps {
  _id: string
  title: string // 标题
  avatar?: ImageProps // 头像
  description: string // 描述
}

export interface PostProps {
  // 文章列表
  _id?: string
  excerpt?: string
  title: string
  content?: string // 内容
  image?: ImageProps | string // 图片
  createdAt?: string // 发布时间
  column: string // 文章id  因为你点开的那个文章和要你的文章 ID做匹配
  author?: string | UserProps
}
// 声明登录错误
export interface GlobalErrorProps {
  status: boolean // 判断提示
  message?: string // 消息提示
}

// 上传完文件
export interface ResponseType<p = []> {
  code: number
  msg: string
  data: p
}
// 如果想在其他页面使用的话导出就可以 全局的
export interface GolbalDataProps {
  columns: ColumnProps[]
  posts: PostProps[]
  user: UserProps
  loading: boolean
  token: string
  error: GlobalErrorProps
}
const store = createStore<GolbalDataProps>({
  state: {
    columns: [],
    posts: [],
    user: {
      // 控制header里面登录注册和已经登陆的开关
      isLogin: false
    },
    loading: false,
    token: localStorage.getItem('token') || '',
    error: { status: false }
  },
  getters: {
    // biggerColumnsLen(state) {
    //   return state.columns.filter((c) => c.id > 2).length;
    // },
    getColumnById: (state) => (id: string) => {
      return state.columns.find((c) => c._id === id)
    },
    getPostById: (state) => (id: string) => {
      return state.posts.filter((post) => post.column === id)
    },
    // 专栏
    getCurrentPost: (state) => (id: number) => {
      return state.posts[id]
    }
  },
  mutations: {
    // 登录
    login (state, rawData) {
      const { token } = rawData.data
      // 把获取的token值保存到localstore
      state.token = token
      localStorage.setItem('token', token)
      // 设置请求头才能访问里面的数据
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      // state.user = { ...state.user, isLogin: true, nickName: "迪迦奥特曼" };
    },
    // 删除token
    logout (state) {
      state.token = ''
      localStorage.removeItem('token')
      delete axios.defaults.headers.common.Authorization
    },
    // 获取用户信息
    fetchCurrentUser (state, rawData) {
      state.user = { isLogin: true, ...rawData.data }
    },
    // 新建文章
    createPost (state, newPost) {
      state.posts.push(newPost)
    },
    // 专栏列表
    fetchColumns (state, rwaData) {
      state.columns = rwaData.data.list
    },
    fetchColumn (state, rwaData) {
      state.columns = [rwaData.data]
    },
    // 文章列表
    fetchPosts (state, rwaData) {
      state.posts = rwaData.data.list
    },
    // 文章详情
    fetchPost (state, rawData) {
      state.posts[rawData.data._id] = rawData.data
    },
    //更新文章
    updatePost(state, { data}) {
      state.posts = state.posts.map(post => {
        if(post._id === data._id) {
          return data
        }else {
          return post
        }
      })
    },
    //删除文章
    deletePost(state, { data }) {  
      state.posts = state.posts.filter(post => post._id !== data.id)
    },
    //删除文章
   
    // 控制loading 效果显示隐藏
    setLoading (state, status) {
      state.loading = status // true和false 的值
    },
    // 错误消息提示  e的类型是golbal  是上面的那个对象
    setError (state, e: GlobalErrorProps) {
      state.error = e
    }
  },
  // actions 类似于mutations
  // actions提交的是mutations,而不是直接改变状态

  actions: {
    // 专栏列表
    async fetchColumns (context) {
      // const { data } = await axios.get("/columns");
      // context.commit("fetchColumns", data);
      // getAndCommit('/columns', 'fetchColumns', context.commit)
      asyncAndCommit('/columns', 'fetchColumns', context.commit)
    },
    // 专栏详情
    async fetchColumn ({ commit }, cid) {
      // axios.get(`/columns/${cid}`).then((resp) => {
      //   commit("fetchColumn", resp.data);
      // });
      // const { data } = await axios.get(`/columns/${cid}`);
      // commit("fetchColumns", data);
      getAndCommit(`/columns/${cid}`, 'fetchColumn', commit)
    },
    // 文章列表
    async fetchPosts ({ commit }, cid) {
      // axios.get(`/columns/${cid}/posts`).then((resp) => {
      //   commit("fetchPosts", resp.data);
      // });
      // const { data } = await axios.get(`/columns/${cid}/posts`);
      // commit("fetchColumns", data);
      getAndCommit(`/columns/${cid}/posts`, 'fetchPosts', commit)
    },
    // 文章详情
    fetchPost ({ state, commit }, id) {
      const currentPost = state.posts[id]
      if (!currentPost || !currentPost.content) {
        return getAndCommit(`/posts/${id}`, 'fetchPost', commit)
      } else {
        return Promise.resolve({ data: currentPost })
      }
    },
    updatePost ({ commit }, { id, payload }) {
      return asyncAndCommit(`/posts/${id}`, 'updatePost', commit, {
        // 请求方式
        method: 'patch',
        data: payload
      })
    },
    deletePost({ commit }, id){
      return asyncAndCommit(`/posts/${id}`, 'deletePost', commit, { method: 'delete'})
    },
    // 登录
    login ({ commit }, payload) {
      return postAndCommit('/user/login', 'login', commit, payload)
    },
    // 获取用户信息
    fetchCurrentUser ({ commit }) {
      getAndCommit('user/current', 'fetchCurrentUser', commit)
    },
    loginAndFecth ({ dispatch }, loginData) {
      return dispatch('login', loginData).then(() => {
        return dispatch('fetchCurrentUser')
      })
    },
    // 新建文章
    createPost ({ commit }, payload) {
      return postAndCommit('/posts', 'createPost', commit, payload)
    }
  },
  modules: {}
})
export default store
